<?php
namespace app\index\controller;
use think\Url;

class Users extends Base{
    private $validate;
    public function _initialize() {
        parent::_initialize();
        $this->validate = validate('Users');//表单验证器
    }

    public function login(){
        // 获取session来判断是否登陆
        $user = $this->getLoginUser();
        if($user && $user->id){
            $this->redirect(url('account/index'));
        }
        return $this->fetch();
    }
    
    public function register(){
        if(request()->isPost()){
            $data = input('post.');
            //严格校验注册表单数据
            if(!$this->validate->scene('register')->check($data)){
                $this->error($this->validate->getError());
            }
            //自动生成 密码的加盐字符串
            $data['pwdcode'] = mt_rand(100,10000);
            $data['password'] = md5($data['password'].$data['pwdcode']);

            //数据入库
            try {
                $user = model('Users')->add($data);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            if($user){
                //把用户信息记录到session
                session('yc_user',$user,'user');
                $this->success('注册成功',url('users/sendCheckEmail'));
            }else{
                $this->error('注册失败');
            }
        } else {
            return $this->fetch();
        }
    }

    public function logincheck(){
        //判定post
        if(!request()->isPost()){
            $this->error('提交不合法');
        }
        //获取表单数据
        $data = input('post.');
        //严格校验登陆表单数据
        if(!$this->validate->scene('login')->check($data)){
            $this->error($this->validate->getError());
        }
        //获取数据库中用户信息
        try{
            $user = model('Users')->getUserByData($data);
        } catch(\Exception $e) {
            $this->error($e->getMessage());
        }
        //把用户信息记录到session
        session('yc_user',$user,'user');
        //判断账号是否激活
        if($user->status == 0){
            $this->redirect(url('users/sendCheckEmail'));
        } else {
            $this->redirect(url('account/index'));
        }
    }

    /**
     * 发送确认邮件
     */
    public function sendCheckEmail(){
        //页面元素加载
        $this->assign('title','邮箱验证激活');
        $this->assign('h1','验证');

        $user = session('yc_user', '', 'user');
        if(!$user || !$user->id){
            $this->error("你还未登录",url('users/login'));
        }
        if(!$user->status == 0) {
            $this->success('你的账号已经激活，不需要再次激活!', url('account/index'));
        } else {
            if(request()->isPost()){
                $emailkey = passport_encrypt($user->user_email);
                $keydate = passport_encrypt(strval(time()));
                $url = Url::build('users/activeAccount', ['emailkey' => $emailkey, 'keydate' => $keydate], true, true);
                $content="注册成功，你在本站注册的邮箱需要验证！请点击<a href='".$url."'>".$url."</a>(或者复制到浏览器打开)，完成验证！";
                $result=sendEmailTo($user->user_email, $user->username, '邮箱验证', $content);
                $this->assign('buttonDisplay',0);
                if($result){
                    $this->assign('message','恭喜您，邮件发送成功！请前往邮箱激活您的账号！谢谢！');
                    return $this->fetch('message');
                }else{
                    $this->assign('message','很抱歉，由于系统出错，无法发送邮件，请联系本网站管理员！谢谢！');
                    return $this->fetch('message');
                }
            } else {
                $this->assign('message','恭喜您，注册成功！你在本站注册的邮箱需要验证，请点击“发送邮件”按钮！谢谢！');
                $this->assign('buttonDisplay',1);
                return $this->fetch('message');
            }
        }
    }

    /**
     * 激活访问函数
     */
    public function activeAccount(){
        $data = input('get.');
        if(!is_array($data) || !$data['keydate'] || !$data['emailkey']){
            $this->error("请求出错！",url('index/index'));
        }
        $email = passport_decrypt($data['emailkey']);
        $keydate = intval(passport_decrypt($data['keydate']));
        $user = model('Users')->where(['user_email' => $email])->find();
        if($user->status == 1){
            $this->success('你的账号已经激活，不需要再次激活!', url('users/index'));
        } else {
            $agotime=(time()-$keydate);
            if($agotime > 3600){
                $this->error("超过10分钟,链接失效,请重新获取邮件",url('users/sendCheckEmail'));
            } else {
                if(model('Users')->updateById(['status'=> 1],$user->id)){
                    session(null,'user');
                    $this->success("账号激活成功！",url('users/login'));
                } else {
                    $this->error("账号激活失败，请重新获取邮件或联系管理员！",url('users/sendCheckEmail'));
                }
            }
        }
    }

    /**
     * 退出登陆函数
     */
    public function logout(){
        session(null,'user');
        $this->redirect(url('users/login'));
    }
}
